package commonusealgorithm;

import java.util.Arrays;

/**
 * @Author PoX21s
 * @Date: 2021/11/1 20:47
 * @Version 1.0
 */

public class Prim {
    public static void main(String[] args) {
        char[] data = new char[]{'A','B','C','D','E','F','G'};
        int verxs = data.length;
        //邻接矩阵的关系使用二维数组表示,10000 这个大数，表示两个点不联通
        int [][]weight=new int[][]{
                {10000,5,7,10000,10000,10000,2},
                {5,10000,10000,9,10000,10000,3},
                {7,10000,10000,10000,8,10000,10000},
                {10000,9,10000,10000,10000,4,10000},
                {10000,10000,8,10000,10000,5,4},
                {10000,10000,10000,4,5,10000,6},
                {2,3,10000,10000,4,6,10000},};

        minTree minTree = new minTree();
        graph graph = new graph(verxs);
        minTree.creatGraph(graph,verxs,data,weight);
        minTree.show(graph);
        minTree.prim(graph,0);
    }

}

class minTree{
    public void creatGraph(graph graph, int verxs, char[] data, int[][] wight){
        int i, j;

        for (i = 0; i < verxs; i++) {
            graph.data[i] = data[i];
            for (j = 0; j < verxs; j++){
                graph.wight[i][j] = wight[i][j];
            }
        }
    }

    public void show(graph graph){
        for (int[] ints : graph.wight) {
            System.out.println(Arrays.toString(ints));
        }
    }

    public void prim(graph graph,int v){
        int[] isVisited = new int[graph.verxs];

        isVisited[v] = 1;
        int h1 = -1;
        int h2 = -1;

        int minWight = 10000;

        for (int i = 1; i < graph.verxs; i++) {
            for (int j = 0; j < graph.verxs; j++) {
                for (int k = 0; k < graph.verxs; k++) {
                    if (isVisited[j] == 1 && isVisited[k] == 0 && graph.wight[j][k] < minWight){
                        minWight = graph.wight[j][k];

                        h1 = j;
                        h2 = k;
                    }
                }
            }
            System.out.println("边<" + graph.data[h1] + "," + graph.data[h2] + "> 权值:" + minWight);
            isVisited[h2] = 1;
            minWight = 10000;
        }
    }

}

class graph{
    int verxs;
    char[] data;
    int[][] wight;

    public graph(int verxs){
        this.verxs = verxs;
        data = new char[verxs];
        wight = new int[verxs][verxs];
    }
}
